package com.youlai.boot.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class ReflectUtils {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    /**
     * 设置对象的指定字段值，支持 String、BigDecimal、LocalDate 类型
     *
     * @param obj       目标对象
     * @param fieldName 字段名
     * @param value     字符串值
     * @param index     当前 Excel 列索引（用于报错提示）
     */
    public static void setFieldValue(Object obj, String fieldName, String value, String index, String sheetName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);

            if (field.getType() == String.class) {
                field.set(obj, value);
            } else if (field.getType() == BigDecimal.class) {
                try {
                    BigDecimal bigDecimal = null;
                    if (StrUtil.isNotBlank(value)) {
                        value = value.replace(",", "");
                        value = value.replace("，", "");
                        bigDecimal = new BigDecimal(value);
                    }
                    field.set(obj, bigDecimal);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(sheetName + "：序号 " + index + "的数据格式错误，期望类型为数字 示例：9.99");
                }
            } else if (field.getType() == LocalDate.class) {
                try {
                    LocalDate localDate = null;
                    if (StrUtil.isNotBlank(value)) {
                        value = value.replace("年", "-");
                        value = value.replace("月", "-");
                        value = value.replace("日", "");
                        value = value.replace("/", "-");
                        localDate = DateUtil.parse(value).toLocalDateTime().toLocalDate();
                    }
                    field.set(obj, localDate);
                } catch (DateTimeParseException e) {
                    throw new IllegalArgumentException(sheetName + "：序号 " + index + " 的数据格式错误，期望类型为日期，格式： yyyy-MM-dd 示例：" + LocalDate.now());
                }
            } else {
                throw new IllegalArgumentException("不支持的字段类型：" + field.getType().getName());
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("设置字段失败：" + fieldName, e);
        }
    }
}